package com.fmc123.base.web;


import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.fmc123.base.config.Constant;
import com.fmc123.base.pesistence.Page;
import com.fmc123.base.utils.DateUtils;
import com.fmc123.base.utils.StringUtils;

/**
 * 
* @ClassName: BaseController
* @Description: 控制器基类，其他控制器可以通过继承此类来获取通用方法。
* @author fmc
* @date 2015年9月13日上午9:04:05
*
 */
@Controller
public  class BaseController  {
	
    private HttpServletRequest request;
    
    private HttpServletResponse response;
  
	/**
	 * 日志对象
	 */
	private static Logger log=LoggerFactory.getLogger(BaseController.class);
	
	@ModelAttribute
	public void initReqAndRes(HttpServletRequest request,HttpServletResponse response){
	  this.request=request;
	  this.response=response;
	}
	
	/**
	 * 表单数据绑定，对表单String参数进行参数Html转义，防止XSS攻击
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder){
	  binder.registerCustomEditor(String.class, new PropertyEditorSupport(){
        @Override
        public String getAsText() {
          Object text=getValue();
         return text!=null?text.toString():"";
        }
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
          setValue(text==null?null:StringEscapeUtils.escapeHtml4(text));
        }
	  });
	  
	  //Date日期转换
	  binder.registerCustomEditor(Date.class, new PropertyEditorSupport(){
	    @Override
        public void setAsText(String text) throws IllegalArgumentException {
          setValue(DateUtils.parseDate(text));
        }
	  });
	  
	  //Timestamp日期转换
      binder.registerCustomEditor(Timestamp.class, new PropertyEditorSupport(){
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
          Date date= DateUtils.parseDate(text);
          setValue(date==null?null:new Timestamp(date.getTime()));
        }
      });
	}
	
	/**
	 * 添加消息
	 * @param model
	 * @param messages
	 */
	public void addMessage(Model model,String...messages){
		StringBuilder sb=new StringBuilder();
		for(String ms:messages){
			sb.append(ms).append(sb.length()>1?"<br/>":"");
		}
		model.addAttribute("messages", sb.toString());
	}

	/**
	 * 返回Integer参数，并制定默认值
	 * @param name
	 * @return
	 */
	public Integer getParamForInt (String name,Integer defaultValue){
	  String value=  request.getParameter(name);
	  if(StringUtils.isBlank(value)){
	    return defaultValue;
	  }
	  return Integer.valueOf(value);
	}
	 
	/**
	 * 返回Integer参数
	 * @param name
	 * @return
	 */
	public Integer getParamForInt(String name){
	  return getParamForInt(name,null);
	}
	
	/**
	 * 返回String参数
	 * @param name
	 * @return
	 */
	public String getParamForString(String name){
	  return request.getParameter(name);
	}
	
	/**
	 * 设置参数到request中
	 * @param name
	 * @param value
	 */
	public void setAttribute(String name,Object value){
	  request.setAttribute(name, value);
	}
	
	/**
	 * 设置分页对象
	 * @return
	 */
	public <T> Page<T> initPage(Class<T> entityClass){
	  //获取分页字段
	  String order_field= getParamForString(Constant.DWZ_PAGE_ORDER_FIELD);
	  //获取分页方向asc,desc
	  String order_direction= getParamForString(Constant.DWZ_PAGE_ORDER_DIRECTION);
	  //创建分页对象
	  Page<T> page=new Page<T>(getParamForInt(Constant.DWZ_PAGE_NUMBER,1),
	      getParamForInt(Constant.DWZ_PAGE_SIZE,Constant.PAGESIZE));
	  //设置分页字段和分页方向
	  page.setOrderBy(order_field);
	  page.setOrderDirection(order_direction);
	  return page;
	}
	
	/**
	 * 获取应用更目录
	 * @return
	 */
	public String getContextPath(){
	  return request.getContextPath();
	}
	
	/**
	 * 返回json数据
	 * 操作成功
	 * @param render
	 */
	public void tojsonOk(Render render){
	  try {
      OutputStream out=response.getOutputStream();
      out.write(render.renderOk().getBytes("UTF-8"));
    } catch (IOException e) {
      e.printStackTrace();
    }
	}
	
	/**
     * 返回json数据
     * 操作失败
     * @param render
     */
    public void tojsonError(Render render){
      try {
      OutputStream out=response.getOutputStream();
      out.write(render.renderError().getBytes("UTF-8"));
    } catch (IOException e) {
      e.printStackTrace();
    }
    }
}
